package com.douyu.ocean.messageSender;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.TreeMap;






import org.apache.commons.codec.digest.DigestUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SmsSender {
	
	private static Logger log = LoggerFactory.getLogger(SmsSender.class);

	private String urlStr;
	private String smsid;
	private String smsKey;
	ResourceBundle bundle;
	
	private HttpURLConnection httpURLConnection;
	private URL url;
	private JSONObject json;

	
	public static void main(String[] args) {
		SmsSender tmp = new SmsSender();
		try {
			tmp.sendSms("bbc", "13026377083");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public SmsSender(){
		bundle = ResourceBundle.getBundle("monitor");
		urlStr = bundle.getString("urlStr");
		smsid = bundle.getString("smsid");
		smsKey = bundle.getString("smsKey");
	}

	public boolean sendSms(String message, String phoneNum) throws NoSuchAlgorithmException, IOException, JSONException{
		log.warn("send message :'" + message +"' to phone : " + phoneNum);
		
		Map<String,String> msg = new TreeMap<String, String>();
		String time = (new SimpleDateFormat("yyyyMMdd-HH_mm_ss")).format(new Date());
		msg.put("smsv1", URLEncoder.encode(message, "UTF-8"));
		msg.put("smsv2", time);
		msg.put("phonenum", phoneNum);
		msg.put("smsid", smsid);
		
		StringBuilder sb = new StringBuilder();
		for(Map.Entry<String, String> entry : msg.entrySet()){
			sb.append(entry.getKey().concat("=").concat(entry.getValue()));
			sb.append("&");
		}
		String ct = new String(sb);
		String content = ct.substring(0,ct.length()-1) + smsKey;
		
		String auth = DigestUtils.md5Hex(content.getBytes());
		sb.append("auth="+auth);
		
		String result = senderRequest(urlStr + "?" + new String(sb));
		
		if(result.equals("") || result.isEmpty()){
			log.error("something wrong with send http");
			return false;
		}else{
			
			json = new JSONObject(result);
			int code = Integer.parseInt(json.getString("error"));
			String data = json.getString("data");
			
			if(code != 0){
				log.error("Wrong response :" + data + ", with code :"+code);
				return false;
			}else{
				log.warn("sended message with response :" + data);
				return true;
			}
		}
	}

	public String senderRequest(String requestUrl) throws IOException {

	
		url = new URL(requestUrl);
		httpURLConnection = (HttpURLConnection) url.openConnection(); // 获取连接
//		httpURLConnection.setRequestMethod("POST"); // 设置请求方法为POST, 也可以为GET
		
		InputStream is = httpURLConnection.getInputStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();
		while (br.read() != -1) {
			sb.append(br.readLine());
		}
		
		String content = new String(sb);
		content = new String(content.getBytes("GB2312"), "ISO-8859-1");
		br.close();
		if(!content.startsWith("{")){
			content = "{".concat(content);
		}
		return content;
	}
}